package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.common.RoleEnum;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.ExcelImportUtil;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.NcgDeviceWatchVO;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 代理商信息 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-27
 */

@Api(value = "代理商信息", tags = "", description = "")
@RestController
@RequestMapping("/health/agent")
public class AgentController {
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private INcgDeviceWatchService deviceWatchService;
    @Autowired
    private IHospitalService hospitalService;
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private IAppProductService productService;
    @Autowired
    private IDepartmentService departmentService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新代理商信息", notes = "新增或更新代理商信息")
    public Result save(@RequestBody Agent agent) {
        SysUserEntity user = new SysUserEntity();
        if (agent.getId() == null) {
            user.setUsername(agent.getName());
            user.setNickName(agent.getAbbreviation());
            user.setType(1);
            user.setPhone(agent.getPhone());
            user.setAddress(agent.getAddress());
            user.setRole("ROLE_AGENT_OPERATION");
            user.setPassword("123456");
            user.setFlag("agent" + UUID.randomUUID().toString().replaceAll("-", ""));
            agent.setFlag(user.getFlag());
            userService.save(user);
        } else {
            user = agentService.getUserByFlag(agent.getFlag());
            // 重新设置用户信息
            user.setUsername(agent.getName());
            user.setNickName(agent.getAbbreviation());
            user.setPhone(agent.getPhone());
            user.setAddress(agent.getAddress());
            userService.saveOrUpdate(user);
        }
        return Result.success(agentService.saveOrUpdate(agent));
    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除代理商信息", notes = "根据ID删除代理商信息")
    public Result delete(@PathVariable Integer id, @RequestParam(required = false, defaultValue = "") String flag) {
        SysUserEntity userByFlag = agentService.getUserByFlag(flag);
        userService.removeById(userByFlag.getUserId());// 同时删除用户表数据
        //20220918 逻辑删除 横向修改 start
        //                UpdateWrapper delData = new UpdateWrapper<User>();
        //                delData.set("isdelete",1);
        //                delData.eq("id",user.getId());
        //                userService.update(delData);
        //20220918 逻辑删除 横向修改 end
        return Result.success(agentService.removeById(id));
    }

    // 根据IDS删除
    @Transactional
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除代理商信息", notes = "根据IDS删除代理商信息")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        try {
            for (Integer id : ids) {
                Agent agent = agentService.getById(id);
                SysUserEntity user = agentService.getUserByFlag(agent.getFlag());
                userService.removeById(user.getUserId());
//20220918 逻辑删除 横向修改 start
//                UpdateWrapper delData = new UpdateWrapper<User>();
//                delData.set("isdelete",1);
//                delData.eq("id",user.getId());
//                userService.update(delData);
//20220918 逻辑删除 横向修改 end
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "删除失败!!!");
        }

        return Result.success(agentService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部代理商信息", notes = "查询全部代理商信息")
    public Result findAll() {
        return Result.success(agentService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录代理商信息", notes = "根据ID查询一条记录代理商信息")
    public Result findOne(@RequestParam Integer id) {
        return Result.success(agentService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询代理商信息", notes = "分页查询代理商信息")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") String searchName,
                           @RequestParam(required = false, defaultValue = "") Long uid) {
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(searchName), "name", searchName);
        if (uid != null) {
            queryWrapper.eq("uid", uid);
        }
        //20220918 逻辑删除 横向修改 start   查询有效数据
//                queryWrapper.eq("isdelete",0);
//20220918 逻辑删除 横向修改 end
        queryWrapper.orderByAsc("id");

        return Result.success(agentService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 分页查询
    @GetMapping("/findDevicePage")
    @ApiOperation(value = "分页查询代理商设备信息", notes = "分页查询代理商设备信息")
    public Result findDevicePage(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam(required = false, defaultValue = "") String searchImei,
                                 @RequestParam(required = false, defaultValue = "") Long loginUid,
                                 @RequestParam(required = false, defaultValue = "") String loginRole,
                                 @RequestParam(required = false, defaultValue = "") Long searchAgentId,
                                 @RequestParam(required = false, defaultValue = "") Long searchHid,
                                 @RequestParam(required = false, defaultValue = "") Long searchType) {
        QueryWrapper<NcgDeviceWatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        queryWrapper.like(StringUtils.isNotBlank(searchImei), "imei", searchImei);
        if (ObjectUtil.isNotEmpty(searchAgentId)){
            queryWrapper.eq("agentid", searchAgentId);
        }
        if (ObjectUtil.isNotEmpty(searchHid)) {
            queryWrapper.eq("hid", searchHid);
        }
        if (ObjectUtil.isNotEmpty(searchHid)) {
            queryWrapper.eq("type", searchType);
        }
        if (ObjectUtil.equals(RoleEnum.ROLE_ADMIN.name(), loginRole)){
            queryWrapper.isNotNull("agentid");
        } else if (ObjectUtil.equals(RoleEnum.ROLE_AGENT.name(), loginRole)){
            List<Agent> agents = null;
            if (loginUid != null){
                QueryWrapper<Agent> wrapper = new QueryWrapper<>();
                wrapper.eq("uid", loginUid);
                agents = agentService.list(wrapper);
            }
            if (CollectionUtils.isNotEmpty(agents)){
                for (int i = 0; i < agents.size(); i++) {
                    if (i == 0){
                        queryWrapper.eq("agentid", agents.get(i).getId());
                    } else {
                        queryWrapper.or().eq("agentid", agents.get(i).getId());
                    }
                }
                queryWrapper.or().eq("agentid", getAgent(loginUid).getId());
            } else {
                Agent agent = getAgent(loginUid);
                queryWrapper.eq("agentid", agent.getId());
            }
        } else if (ObjectUtil.equals(RoleEnum.ROLE_AGENT_OPERATION.name(), loginRole)){
            Agent agent = getAgent(loginUid);
            queryWrapper.eq("agentid", agent.getId());
        }
        IPage<NcgDeviceWatch> page = deviceWatchService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<NcgDeviceWatchVO> ncgDeviceWatchVOS = MyBeanUtil.collectionCopy(page.getRecords(), NcgDeviceWatchVO.class);
        Page<NcgDeviceWatchVO> result = new Page<>();
        result.setRecords(ncgDeviceWatchVOS);
        result.setTotal(page.getTotal());
        for (NcgDeviceWatchVO device : result.getRecords()) {
            if (ObjectUtil.isNotEmpty(device.getHid())) {
                Hospital hospital = hospitalService.getById(device.getHid());
                device.setHName(ObjectUtil.isEmpty(hospital.getName()) ? hospital.getAbbreviation() : hospital.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getAgentid())) {
                Agent agent = agentService.getById(device.getAgentid());
                device.setAgentName(ObjectUtil.isEmpty(agent.getName()) ? agent.getAbbreviation() : agent.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getStatus())) {
                if(device.getStatus() == 2) {
                    device.setStatusName("使用中");
                }else if(device.getStatus() == 3) {
                    device.setStatusName("空闲中");
                }else{

                }
            }
            if (ObjectUtil.isNotEmpty(device.getProductid())) {
                AppProduct product = productService.getById(device.getProductid());
                device.setProductName(product.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getDepartmentid())) {
                Department department = departmentService.getById(device.getDepartmentid());
                device.setDepartmentName(department.getName());
            }
        }
        return Result.success(result);
    }

    @GetMapping("/getDeviceUseRecord")
    public Result getDeviceUseRecord(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                                     @RequestParam(required = false, defaultValue = "") String loginRole,
                                     @RequestParam(required = false, defaultValue = "") String imei,
                                     @RequestParam(required = false,defaultValue = "")Long userId) {

        if (ObjectUtil.isNull(getAgent(userId))) {

            System.out.println(loginRole);
            if (loginRole.equals(RoleEnum.ROLE_H_D_ADMIN.name())) {
                //设备科管理员
                SysUserEntity ssUser = userService.getById(userId);
                List<Recordset> recordList = agentService.getDeviceUserRecordByHid(ssUser.getHid());
                recordList.forEach(one -> {
                    if (ObjectUtil.isNotEmpty(one.getUid())) {
                        SysUserEntity user = userService.getRedisByUid(one.getUid() + "");
                        if(ObjectUtil.isNull(user)){
                            one.setUName("无患者信息");
                        }else{
                            one.setUName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                        }
                    }
                    if (ObjectUtil.isNotEmpty(one.getDocid())) {
                        SysUserEntity user = userService.getRedisByUid(one.getDocid());
                        if(ObjectUtil.isNull(user)){
                            one.setDocName("无医生信息");
                        }else {
                            one.setDocName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                        }
                    }
                    if (ObjectUtil.isNotEmpty(one.getImei())) {
                        NcgDeviceWatch device = deviceWatchService.getDeviceByDevNo(one.getImei());
                        AppProduct product = productService.getById(device.getProductid());
                        if(ObjectUtil.isNull(device)){
                            one.setDevicename("无产品编号");
                        }else{
                            one.setDevicename(ObjectUtil.isEmpty(device.getDevicename()) ? "" : device.getDevicename());
                        }
                        if(ObjectUtil.isNull(product)){
                            one.setProductName("无产品名称");
                        }else{
                            one.setProductName(ObjectUtil.isEmpty(product.getName()) ? "" : product.getName());
                        }
                    }
                });
                Page<Recordset> result = new Page<>();
                result.setRecords(recordList);
                result.setTotal(recordList.size());

                return  Result.success(result);

            }else {

                QueryWrapper<Recordset> queryWrapper = new QueryWrapper<Recordset>()
                        .ge( "status",0);
//            ROLE_H_D_ADMIN
                Page<Recordset> page = recordsetService.page(new Page<>(pageNum, pageSize), queryWrapper);

                List<Recordset> recordList = MyBeanUtil.collectionCopy(page.getRecords(), Recordset.class);
                recordList.forEach(one -> {
                    if (ObjectUtil.isNotEmpty(one.getUid())) {
                        SysUserEntity user = userService.getRedisByUid(one.getUid());
                        if(ObjectUtil.isNull(user)){
                            one.setUName("无患者信息");
                        }else{
                            one.setUName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                        }
                    }
                    if (ObjectUtil.isNotEmpty(one.getDocid())) {
                        SysUserEntity user = userService.getRedisByUid(one.getDocid());
                        if(ObjectUtil.isNull(user)){
                            one.setDocName("无医生信息");
                        }else{
                            one.setDocName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                        }
                    }
                    if (ObjectUtil.isNotEmpty(one.getImei())) {
                        NcgDeviceWatch device = deviceWatchService.getDeviceByDevNo(one.getImei());
                        AppProduct product = productService.getById(device.getProductid());
                        if(ObjectUtil.isNull(device)){
                            one.setDevicename("无产品编号");
                        }else{
                            one.setDevicename(ObjectUtil.isEmpty(device.getDevicename()) ? "" : device.getDevicename());
                        }
                        if(ObjectUtil.isNull(product)){
                            one.setProductName("无产品名称");
                        }else{
                            one.setProductName(ObjectUtil.isEmpty(product.getName()) ? "" : product.getName());
                        }
                    }
                });
                Page<Recordset> result = new Page<>();
                result.setRecords(recordList);
                result.setTotal(page.getTotal());

                return  Result.success(result);

            }

        }else {

            List<Recordset> recordList = agentService.getDeviceUserRecordByAgentid(getAgent(userId).getId());
            recordList.forEach(one -> {
                if (ObjectUtil.isNotEmpty(one.getUid())) {
                    SysUserEntity user = userService.getRedisByUid(one.getUid());
                    if(ObjectUtil.isNull(user)){
                        one.setUName("无患者信息");
                    }else{
                        one.setUName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                    }
                }
                if (ObjectUtil.isNotEmpty(one.getDocid())) {
                    SysUserEntity user = userService.getRedisByUid(one.getDocid());
                    if(ObjectUtil.isNull(user)){
                        one.setDocName("无医生信息");
                    }else {
                        one.setDocName(ObjectUtil.isEmpty(user.getUsername()) ? "" : user.getUsername());
                    }
                }
                if (ObjectUtil.isNotEmpty(one.getImei())) {
                    NcgDeviceWatch device = deviceWatchService.getDeviceByDevNo(one.getImei());
                    AppProduct product = productService.getById(device.getProductid());
                    if(ObjectUtil.isNull(device)){
                        one.setDevicename("无产品编号");
                    }else{
                        one.setDevicename(ObjectUtil.isEmpty(device.getDevicename()) ? "" : device.getDevicename());
                    }
                    if(ObjectUtil.isNull(product)){
                        one.setProductName("无产品名称");
                    }else{
                        one.setProductName(ObjectUtil.isEmpty(product.getName()) ? "" : product.getName());
                    }
                }
            });
            Page<Recordset> result = new Page<>();
            result.setRecords(recordList);
            result.setTotal(recordList.size());

            return  Result.success(result);

        }
    }

    /**
     *  根据用户ID获取代理商
     * @param loginUid
     * @return
     */
    private Agent getAgent(Long loginUid) {
        SysUserEntity user = userService.getById(loginUid);
        Agent agent = agentService.getAgentByFlag(user.getFlag());
        return agent;
    }

    // 新增或更新
    @PostMapping("/saveDevice")
    @ApiOperation(value = "新增或更新代理商信息", notes = "新增或更新代理商信息")
    public Result saveDevice(@RequestBody NcgDeviceWatch ncgDeviceWatch) {

        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(ncgDeviceWatch.getImei()), "imei", ncgDeviceWatch.getImei());

        NcgDeviceWatch watches = deviceWatchService.getOne(wrapper);

        if (ObjectUtil.isNotEmpty(watches) && ObjectUtil.notEqual(watches.getImei(), ncgDeviceWatch.getImei())) {
            return Result.error(Constants.CODE_500, "设备已存在!");
        }

        if (ObjectUtil.isEmpty(ncgDeviceWatch.getId())) {
            ncgDeviceWatch.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            ncgDeviceWatch.setCreatetime(LocalDateTime.now());
            ncgDeviceWatch.setIsdelete(0);
            ncgDeviceWatch.setIsenable(0);
            if (ObjectUtil.isEmpty(ncgDeviceWatch.getAgentid())){
                ncgDeviceWatch.setAgentid(getAgent(ncgDeviceWatch.getUid()).getId());
            }
            ncgDeviceWatch.setUid(null);
            ncgDeviceWatch.setDepartmentid(ncgDeviceWatch.getDepartmentid());
        } else {
            ncgDeviceWatch.setUpdatetime(LocalDateTime.now());
            ncgDeviceWatch.setUid(null);
        }
        return Result.success(deviceWatchService.saveOrUpdate(ncgDeviceWatch));
    }

    /**
     * 代理商或代理商运营人员将设备分配到医院
     */
    @GetMapping("/binding")
    @ApiOperation(value = "代理商或代理商运营人员将设备分配到医院", notes = "代理商或代理商运营人员将设备分配到医院")
    public Result binding(@RequestParam Long hid,
                          @RequestParam Long uid,
                          @RequestParam Long deviceid){
        Agent agent = getAgent(uid);
        Integer num = agentService.bindingHospital(deviceid, hid, agent.getId());
        if (num > 0){
            return Result.success("分配医院成功");
        } else {
            return Result.error(Constants.CODE_500, "分配失败，请联系管理员");
        }
    }

    /**
     *
     * 将设备下发到运营人员
     */
    @GetMapping("/editOperation")
    @ApiOperation(value = "将设备下发到运营人员", notes = "将设备下发到运营人员")
    public Result editOperation(@RequestParam Long agentid,@RequestParam Long deviceid){
        Integer num = agentService.editOperation(deviceid, agentid);
        if (num > 0){
            return Result.success("设备分配成功");
        } else {
            return Result.error(Constants.CODE_500, "分配失败，请联系管理员");
        }
    }

    /**insertBath
     * 代理商导入设备
     */
    @PostMapping("/insertBath")
    public Result insertBath(MultipartFile file, @RequestParam(required = false, defaultValue = "") Long uid) {
        NcgDeviceWatchVO vo = new NcgDeviceWatchVO();

        NcgDeviceWatch ncgDeviceWatch = new NcgDeviceWatch();

        List<List<String>> lists = ExcelImportUtil.importExcel(file);
        if (CollectionUtils.isEmpty(lists)) {
            return Result.error(Constants.CODE_500, "导入失败,请检查文件!!!");
        }
        int succ = 0;
        List<Integer> errLine = new ArrayList<>();

        try {
            for (int i = 0; i < lists.size(); i++) {
                vo.setImei(lists.get(i).get(0));
                vo.setCycle(Integer.parseInt(lists.get(i).get(1)));
                Agent agent = filterOperation(lists.get(i).get(2));
                if (ObjectUtil.isEmpty(agent)){
                    errLine.add(i);
                } else {
                    vo.setAgentid(agent.getId());
                }
                switch (lists.get(i).get(3)) {
                    case "智能手表":
                        vo.setType("1");
                        break;
                    case "血压计":
                        vo.setType("2");
                        break;
                    case "血糖血压仪":
                        vo.setType("3");
                        break;
                    case "心电":
                        vo.setType("4");
                        break;
                    default:
                        vo.setStatus(0);
                        break;
                }
                vo.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                vo.setCreatetime(LocalDateTime.now());
                vo.setIsdelete(0);
                vo.setIsenable(0);
                vo.setStatus(0);
                vo.setId(null);
                BeanUtil.copyProperties(vo, ncgDeviceWatch);
                deviceWatchService.save(ncgDeviceWatch);
                succ += 1;
            }
            return Result.success("成功导入" + succ + "条,失败" + errLine.size() + "条,在" + errLine + "行");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "导入失败!!!");
        }
    }

    private Agent filterOperation(String agentName) {
        return agentService.filterOperation(agentName);
    }

}

